package com.sencorsta.ids.gateway.http;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.common.service.Regular;
import com.sencorsta.ids.common.service.ServerKey;
import com.sencorsta.ids.common.service.ServerVerify;
import com.sencorsta.ids.core.configure.SysConfig;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.http.HttpHandler;
import com.sencorsta.utils.net.HttpRequester;
import com.sencorsta.utils.net.HttpRespons;
import com.sencorsta.utils.string.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;

import java.io.IOException;

/**
* @description: TODO
* @author TAO
* @date 2019/11/12 16:28
*/
public class GetCode extends HttpHandler implements RedisService {
    @Override
    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.debug("-----------------获取手机验证码-------------------------");
        String phone = params.getString("phone");//手机号码
        //手机号非空
        if (StringUtil.isEmpty(phone)){
            return error(ErrorCodeList.PHONE_IS_NULL);
        }
        //手机号码验证
        if (!Regular.phone(phone)){
            return error(ErrorCodeList.PHONE_NUMBER_ERROR);
        }

        HttpRequester req = new HttpRequester();
        HttpRespons res = new HttpRespons();
        try {
            //获取公钥加密的数据
            JSONObject args= ServerKey.Verify();
            //公钥有误  加密失败
            args.put("phone",phone);
            if (args==null){
                return error(ErrorCodeList.PUBLICKEY_IS_ERROR);
            }
            res=req.sendPost(SysConfig.getInstance().get("ac.GetCode"),args);
            JSONObject jsz=JSONObject.parseObject(res.getContent());
            if (!"0".equals(String.valueOf(jsz.get("code")))){
                return res.getContent();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        return success();
    }

    @Override
    public String doGet(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return doPost(ctx, request, params);
    }


    @Override
    public String getPath() {
        return "/Gateway/GetCode";
    }
}
